package com.dabaozhan.common.utils;

import com.alibaba.fastjson.JSONObject;
import com.dabaozhan.modules.wx_app.base.ResponseDto;
import com.dabaozhan.modules.wx_app.entity.SiteIndustryEntity;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.List;

/**
 * @author houzhong
 * @date 2019-01-09 19:00
 */
public class UploadFile {


    public static JSONObject uploadFile(HttpServletRequest request,String pathUrl) throws Exception {

        JSONObject jsonObject = null;

        System.out.println("进入uploadFile方法！");

        //获取文件需要上传到的路径
        //String pathUrl = request.getSession().getServletContext().getRealPath("/") + ("fileImage/");

        String userId = "";
        File dir = new File(pathUrl);
        if (!dir.exists()) {
            dir.mkdir();
        }

        request.setCharacterEncoding("utf-8");  //设置编码
        //获得磁盘文件条目工厂
        DiskFileItemFactory factory = new DiskFileItemFactory();

        //如果没以下两行设置的话,上传大的文件会占用很多内存，
        //设置暂时存放的存储室,这个存储室可以和最终存储文件的目录不同
        /**
         * 原理: 它是先存到暂时存储室，然后再真正写到对应目录的硬盘上，
         * 按理来说当上传一个文件时，其实是上传了两份，第一个是以 .tem 格式的
         * 然后再将其真正写到对应目录的硬盘上
         */
        factory.setRepository(dir);
        //设置缓存的大小，当上传文件的容量超过该缓存时，直接放到暂时存储室
        factory.setSizeThreshold(1024 * 1024);
        //高水平的API文件上传处理
        ServletFileUpload upload = new ServletFileUpload(factory);
        try {
            List<FileItem> list = upload.parseRequest(request);
            FileItem picture = null;
            for (FileItem item : list) {
                //获取表单的属性名字
                //String name = item.getFieldName();
                //如果获取的表单信息是普通的 文本 信息
                if (item.isFormField()) {
                    //获取用户具体输入的字符串
                    userId = item.getString();
                    System.out.println("userId------" + userId);
                } else {
                    picture = item;
                }
            }
            //获取文件名称
            String originFileName = picture.getName();
            //获取图片后缀
            String suffix = FileType.getSuffixByFilename(originFileName);
            //重命名
            String targetFileName = (new Date()).getTime() + suffix;

            //真正写到磁盘上
            File file = new File(pathUrl + targetFileName);

            OutputStream out = new FileOutputStream(file);
            InputStream in = picture.getInputStream();
            int length = 0;
            byte[] buf = new byte[1024];
            // in.read(buf) 每次读到的数据存放在buf 数组中
            while ((length = in.read(buf)) != -1) {
                //在buf数组中取出数据写到（输出流）磁盘上
                out.write(buf, 0, length);
            }
            in.close();
            out.close();


            jsonObject.put("pathUrl",pathUrl);
            jsonObject.put("targetFileName",targetFileName);
            jsonObject.put("userId",userId);

        } catch (FileUploadException e1) {
        } catch (Exception e) {
        }

        return jsonObject;
    }

    /**
     * 文件上传
     * @param files
     * @param pathUrl
     * @return
     * @throws Exception
     */
    public static JSONObject uploadFileImg(MultipartFile[] files, String pathUrl) throws Exception {
        JSONObject jsonObject = new JSONObject();
        if (files != null && files.length > 0) {
            for(int i = 0;i<files.length;i++){
                MultipartFile file = files[i];
                if(!file.isEmpty()) {
                    //logger.info("成功获取照片");
                    String fileName = file.getOriginalFilename();

                    String type = fileName.indexOf(".") != -1 ? fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()) : null;
                    // logger.info("图片初始名称为：" + fileName + " 类型为：" + type);
                    if (type != null) {
                        // 自定义的文件名称
                        String trueFileName = String.valueOf(System.currentTimeMillis()) + "."+type;
                        // 设置存放图片文件的路径
                        String path = pathUrl + trueFileName;
                        //logger.info("存放图片文件的路径:" + path);
                        file.transferTo(new File(path));

                        jsonObject.put("pathUrl",path);
                        jsonObject.put("targetFileName",trueFileName);
                    }
                }
            }
        }
        return jsonObject;
    }
}
